有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java工厂模式是正确的模式吗?

我有一个要求,基类方法需要进一步细分。需要注册类对象。根据配置,我将决定实例化哪个类

class Base {
    Base () { }
    void methodOverride() { // do something; }
}

class Derived1 extends Base {
    Derived1 () {
        super();
    }

    void methodOverride() { // specialize }
}

class Derived2 extends Base {
    Derived2 () {
        super();
    }

    void methodOverride() { // specialize }
}

class SelectorFactory {

    Base createClass( int type) {
        switch (type) {
          case DERIVED_1:
             return new Derived1();
          case DERIVED_2:
             return new Derived2();
          case BASE:
             return new Base();
        }
    } 
}

public static void main(String[] args){
    // read configuration
    int type = config.getIntType();

    SelectorFactory factory = new SelectorFactory();
    someRegisterMethod( factory.createClass(type) );
}

问题: 1.你认为有没有其他方法可以实现这一点?这是这种设计模式的最佳用途吗


共 (0) 个答案